#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#include <media.h>
#include <mediaplayer.h>
#include <time.h>
#include <yoc/mic.h>

#include "audio_res.h"

typedef struct _local_audio_info {
    char *path;
}local_audio_info_t;

static local_audio_info_t audio_res[] = {
    AUDIO_RES_ARRAY
};

static local_audio_info_t audio_wakeup_res[] = {
    AUDIO_WAKEUP_RES_ARRAY
};

static int wakeup_audio_play = 0;

int local_audio_play_imp(local_audio_info_t *audios, local_audio_name_t name, int resume)
{
    char local_url[64];
    uint32_t addr;

    addr = (uint32_t)audios[name].path;

    snprintf(local_url, sizeof(local_url), "file://%s", addr);

    return mplayer_start(SOURCE_LOCAL, MEDIA_SYSTEM, local_url, 0, resume);
}

int local_audio_play(local_audio_name_t name)
{
    return local_audio_play_imp(audio_res, name, 1);
}

int local_wakeup_audio_play(local_wakeup_audio_name_t name)
{
    int ret;

    if (name < 0 || name >= LOCAL_AUDIO_WAKEUP_END) {
        time_t curtime = time(NULL);
        name = curtime % LOCAL_AUDIO_WAKEUP_END;
    }

    aui_mic_control(MIC_CTRL_WAKEUP_START);
    ret = local_audio_play_imp(audio_wakeup_res, name, 0);
    if (ret == 0) {
        wakeup_audio_play = 1;
    } else {
        aui_mic_control(MIC_CTRL_WAKEUP_END);
    }

    return ret;
}

void local_audio_finish_check()
{
    if (wakeup_audio_play) {
        aui_mic_control(MIC_CTRL_WAKEUP_END);
        wakeup_audio_play = 0;
    }
}
